<template>
  <div>
    <SearchForm
      @search="onSearch"
      @reset="onReset"
      :search-list="searchList" 
      :search-params="searchParams">
    </SearchForm>

    <div class="table-layout">
      <el-card shadow="never">
        <div class="table-handle">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="onAdd">添加</el-button>
        </div>
        <div class="table-box">
          <el-table
            size="large"
            stripe
            border
            v-loading="loading"
            max-height="500px"
            :data="tableData"
            row-key="id"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.8)"
          >
            <el-table-column align="center" label="ID" width="80" prop="id" />
            <el-table-column width="180" align="center" label="图片">
              <template slot-scope="scope">
                <el-image 
                  style="width: 150px; height: 80px" 
                  :src="scope.row.image_url" 
                  :preview-src-list="[scope.row.image_url]">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column width="200" align="left" label="标题" prop="title" />
            <el-table-column width="100" align="center" label="排序" prop="sort" />
            <el-table-column class-name="status-col" label="状态" width="110" align="center">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                  {{ scope.row.status === 1 ? '显示' : '隐藏' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="230" fixed="right">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="onEdit(scope.row)">编辑</el-button>
                <el-button
                  v-if="scope.row.status === 0"
                  size="mini"
                  type="text"
                  style="color: #67C23A"
                  @click="handleModifyStatus(scope.row, 1)"
                >
                  显示
                </el-button>
                <el-button
                  v-if="scope.row.status === 1"
                  size="mini"
                  type="text"
                  style="color: #E6A23C"
                  @click="handleModifyStatus(scope.row, 0)"
                >
                  隐藏
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  style="color: #F56C6C"
                  @click="onDelete(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      <div class="page-box">
        <el-pagination
          background
          :current-page="pageNo"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize"
          @size-change="changePageSize"
          @current-change="changePageNo"
        />
      </div>
    </div>

    <!-- 轮播图表单对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-width="100px" style="width: 80%; margin: 0 auto;">
        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="图片" prop="image_url">
          <UploadFile v-model="temp.image_url"></UploadFile>
          <div class="el-upload__tip">建议尺寸: 1920px * 500px</div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="temp.sort" :min="1" :max="99" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="temp.status">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crud from "@/mixins/crud";
import {http} from "@/api";
import SearchForm from "@/components/SearchForm"
import UploadFile from '@/components/UploadFile'
export default {
  name: 'Carousels',
  mixins: [crud],
  components: { SearchForm, UploadFile },
    filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'info'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableData: [],
      loading: false,
      pageNo: 1,
      pageSize: 10,
      pageSizes: [10, 20, 30, 40, 50],
      totalSize: 0,
      searchParams: {
        keyword: '',
        status: ''
      },
      defaultParams: {},
      searchList: [
        {
          label: '标题',
          prop: 'keyword',
          name: 'input',
          clearable: true
        },
        {
          label: '状态',
          prop: 'status',
          name: 'select',
          clearable: true,
          options: [
            { label: '显示', value: 1 },
            { label: '隐藏', value: 0 }
          ]
        }
      ],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑轮播图',
        create: '添加轮播图'
      },
      temp: {
        id: undefined,
        title: '',
        image_url: '',
        sort: 1,
        status: 1
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        image_url: [{ required: true, message: '请上传图片', trigger: 'change' }],
      },
      request: http.carousels,
      deleteKey: 'id',
      manual: false
    }
  },
  created() {
    this.initSetting()
    if (!this.manual) {
      this.initData()
    }
  },
  methods: {
    initSetting() {
      // 在获取分页数据前的初始化设置
    },
    formatTableData(tableData) {
      // 可以在这里对表格数据进行处理
      return tableData
    },
    getQueryParams() {
      const params = {
        pageNum: this.pageNo,
        pageSize: this.pageSize,
        ...this.defaultParams
      }
      
      if (this.searchParams.keyword) {
        params.title = this.searchParams.keyword
      }
      
      if (this.searchParams.status !== '') {
        params.status = this.searchParams.status
      }
      
      return params
    },
    onAdd() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    onEdit(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        image_url: '',
        sort: 1,
        status: 1
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.request.create(null,this.temp).then(() => {
            this.dialogFormVisible = false
            this.$message({
              message: '创建成功',
              type: 'success'
            })
            this.onSearch()
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          this.request.update(tempData.id, tempData).then(() => {
            this.dialogFormVisible = false
            this.$message({
              message: '更新成功',
              type: 'success'
            })
            this.onSearch()
          })
        }
      })
    },
    onDelete(row) {
      this.$confirm('确认删除该轮播图?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.delete(row.id).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.onSearch()
        })
      }).catch(() => {
        // 取消删除
      })
    },
    handleModifyStatus(row, status) {
      const statusText = status === 1 ? '显示' : '隐藏'
      this.$confirm(`确认将该轮播图设为${statusText}状态?`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.carousels.update(row.id, { status }).then(() => {
          this.$message({
            message: '状态更新成功',
            type: 'success'
          })
          row.status = status
        })
      }).catch(() => {
        // 取消操作
      })
    }
  }
}
</script>

<style scoped lang="scss">
.table-layout {
  margin-top: 20px;
}

.table-handle {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.table-box {
  margin-bottom: 20px;
}

.page-box {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.el-image {
  border-radius: 4px;
  overflow: hidden;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
